<template>
  <div class="user-detail-page">
    <main>
      <div class="header">
        <p class="title">用户信息</p>
        <div class="search-container">
          <div class="search-input">
            <ul>
              <li
                :class="tabId === '1' ? 'active' : ''"
                @click="handleSwitch('1')"
              >
                基础信息
              </li>
              <li
                :class="tabId === '2' ? 'active' : ''"
                @click="handleSwitch('2')"
              >
                项目信息
              </li>
              <li
                :class="tabId === '3' ? 'active' : ''"
                @click="handleSwitch('3')"
              >
                组织信息
              </li>
            </ul>
            <div v-show="tabId === '2'" class="input-container">
              <el-input
                placeholder="项目名称/项目简称"
                v-model="condition"
              ></el-input>
              <el-button
                class="search-btn"
                type="primary"
                @click="handleSearch"
              >
                <i class="el-icon-search"></i>
              </el-button>
              <el-button type="primary" @click="handleRefresh">
                <i class="el-icon-refresh"></i>
              </el-button>
            </div>
          </div>
          <div class="btns">
            <template v-if="tabId === '2'">
              <el-button
                v-if="hasTabAdd"
                type="primary"
                @click="associationProject"
              >
                新增所属项目
              </el-button>
            </template>
            <template v-else-if="tabId === '3'">
              <el-button
                v-if="hasTabEdit"
                type="primary"
                @click="handleEditOrg"
              >
                编辑
              </el-button>
              <el-button v-if="hasTabSet" type="primary" @click="setOrg">
                关联机构
              </el-button>
            </template>
            <el-button @click="$router.back()">返回</el-button>
          </div>
        </div>
      </div>
      <div class="table-container">
        <div v-show="tabId === '1'" class="content">
          <el-row>
            <el-col :span="12">
              <span class="label">姓名：</span>
              <span class="value">{{ userData.userName || "" }}</span>
            </el-col>
            <el-col :span="12">
              <span class="label">性别：</span>
              <span class="value">{{ userData.gender || "" }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <span class="label">联系方式：</span>
              <span class="value">{{ userData.telephoneNumber || "" }}</span>
            </el-col>
            <el-col :span="12">
              <span class="label">邮箱：</span>
              <span class="value">{{ userData.emailAddress || "" }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <span class="label">用户名：</span>
              <span class="value">{{ userData.userId || "" }}</span>
            </el-col>
            <!--            <el-col :span="12">-->
            <!--              <span class="label">账号：</span>-->
            <!--              <span class="value">{{ userData.userName || ''}}</span>-->
            <!--            </el-col>-->
          </el-row>
        </div>
        <div v-show="tabId === '2'" class="content">
          <el-table v-loading="tableLoading" :data="projectList" row-key="uuid">
            <el-table-column
              label="序号"
              type="index"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="projectName"
              label="项目名称"
            ></el-table-column>
            <el-table-column
              prop="projectAbbreviation"
              label="项目简称"
            ></el-table-column>
            <el-table-column prop="roleName" label="角色">
              <template slot-scope="scope">
                {{ (scope.row.sysRole && scope.row.sysRole.roleName) || "" }}
              </template>
            </el-table-column>
            <el-table-column prop="是否启用" label="是否启用">
              <template slot-scope="scope">
                <span style="display: none;"></span>
                <span v-if="!hasTableLink">{{
                  scope.row.enableFlag === "1" ? "是" : "否"
                }}</span>
                <el-switch
                  v-else-if="scope.row.sysRoleUsers"
                  :disabled="scope.row.switchDisabled"
                  :value="scope.row.enableFlag"
                  @change="
                    v => handleSwitchChange(v, scope.row, scope['$index'])
                  "
                  active-value="1"
                  inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="action" label="操作">
              <template slot-scope="scope">
                <span style="display: none;"></span>
                <el-button
                  v-if="hasTablePermission && scope.row.sysRoleUsers"
                  type="primary"
                  size="small"
                  @click="setPermissions(scope.row)"
                >
                  权限
                </el-button>
                <el-button
                  v-if="hasTableEdit"
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="hasTableDel"
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
            <div class="empty-content" slot="empty">
              <i class="iconfont iconwushuju"></i>
              <p>暂无数据</p>
            </div>
          </el-table>
          <!--          <el-pagination-->
          <!--            v-if="total > 10"-->
          <!--            :page-size="pageSize"-->
          <!--            :current-page="pageNo"-->
          <!--            layout="total, sizes, prev, pager, next, jumper"-->
          <!--            :total="total"-->
          <!--            @size-change="handleSizeChange"-->
          <!--            @current-change="handleCurrentChange"-->
          <!--          />-->
        </div>
        <div v-show="tabId === '3'" class="content tree">
          <el-tree
            :data="orgData"
            default-expand-all
            :current-node-key="selectKey"
            :indent="0"
            node-key="id"
            ref="tree"
            :highlight-current="true"
            :expand-on-click-node="false"
            :props="{
              children: 'children',
              label: 'orgName'
            }"
            @node-click="handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <div class="node-item">
                <p><span class="label">机构名称：</span>{{ node.label }}</p>
                <p>
                  <span class="label">机构简称：</span>{{ data.orgAbbr || "" }}
                </p>
                <p>
                  <span class="label">机构简介：</span>{{ data.orgIntro || "" }}
                </p>
              </div>
            </span>
          </el-tree>
        </div>
      </div>
      <edit-project
        :visible="visible"
        :type="type"
        :options="currentData"
        :loading="loading"
        @cancel="visible = false"
        @submit="handleSave"
      >
      </edit-project>
      <association-project
        :visible="projectVisible"
        :loading="projectLoading"
        :userId="userId"
        @cancel="projectVisible = false"
        @submit="saveProject"
      >
      </association-project>
      <association-org
        :visible="orgVisible"
        :userId="userId"
        :options="currentOrgData"
        :loading="orgLoading"
        @cancel="orgVisible = false"
        @submit="saveAssociationOrg"
      >
      </association-org>
      <edit-org
        :visible="eidtOrgVisible"
        :loading="eidtOrgLoading"
        :options="currentOrgData"
        @cancel="eidtOrgVisible = false"
        @submit="saveOrg"
      >
      </edit-org>
    </main>
  </div>
</template>

<script>
import editProject from "@/components/corp/editProject";
import associationOrg from "@/components/corp/associationOrg";
import associationProject from "@/components/corp/associationProject";
import editOrg from "@/components/corp/editOrg";

export default {
  components: {
    editOrg,
    editProject,
    associationOrg,
    associationProject
  },
  data() {
    return {
      tabId: "1",
      condition: "",
      hasSearch: false,
      pageNo: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      tableLoading: false,
      downloadLoading: false,
      loading: false,
      visible: false,
      type: "",
      currentData: {},
      userData: {},
      projectList: [],
      orgData: [],
      selectKey: "",
      currentOrgData: {},
      // 权限
      roleVisible: false,
      roleLoading: false,
      // 关联项目
      projectVisible: false,
      projectLoading: false,
      // 关联机构
      orgVisible: false,
      orgLoading: false,
      // 编辑机构
      eidtOrgVisible: false,
      eidtOrgLoading: false
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo;
    },
    userId() {
      return this.$route.query.id || "";
    }
  },
  watch: {
    tabId(id) {
      if (id === "1") {
        this.getUserInfoById();
      } else if (id === "2") {
        this.getUserProject();
      } else {
        this.getOrgById();
      }
    }
  },
  created() {
    this.getUserInfoById();
  },
  methods: {
    /**
     * 根据用户信息
     */
    async getUserInfoById() {
      if (!this.userId) return;
      const params = {
        userId: this.userId
      };
      const {
        success,
        data: { data }
      } = await this.$Model.getUserInfoById(params);
      if (success && data) {
        this.userData = data;
      }
    },
    /**
     * 根据用户获取项目列表
     */
    async getUserProject() {
      if (!this.userId) return;
      const params = {
        userId: this.userId
      };
      if (this.hasSearch) params.condition = this.condition;
      this.tableLoading = true;
      const {
        success,
        data: { data }
      } = await this.$Model.getUserProject(params);
      this.tableLoading = false;
      if (success) {
        const list = data || [];
        this.projectList = list.map(item => {
          const roles =
            Array.isArray(item.sysRoleUsers) && item.sysRoleUsers[0];
          return {
            ...item,
            sysRole: roles.sysRole || {},
            // 0：不启用；1：启用
            enableFlag: roles ? roles.enableFlag : "0"
          };
        });
      }
    },
    /**
     * 根据用户获取组织机构信息
     */
    async getOrgById() {
      if (!this.userId) return;
      const params = {
        userId: this.userId
      };
      const {
        success,
        data: { data }
      } = await this.$Model.getOrgTreeByUser(params);
      if (success && data && data.length) {
        this.orgData = data;
        if (this.selectKey) {
          const hasKey = this.checkSelectKey(data, this.selectKey);
          hasKey &&
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.selectKey);
            });
          return;
        }
        this.currentOrgData = {};
      }
    },
    // 校验key
    checkSelectKey(data, key) {
      return (
        (Array.isArray(data) &&
          data.some(item => {
            const { children, id } = item;
            if (id === key) return true;
            return this.checkSelectKey(children, key);
          })) ||
        false
      );
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getTableData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getTableData();
    },
    /**
     * 清除
     */
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
    },
    /**
     * 切换
     */
    handleSwitch(type) {
      this.tabId = type;
    },
    /**
     * 刷新
     */
    handleSearch() {
      this.hasSearch = true;
      this.clear();
      this.getUserProject();
    },
    /**
     * 重置
     */
    handleRefresh() {
      this.hasSearch = false;
      this.clear();
      this.getUserProject();
    },
    /**
     * 新增所属项目
     */
    associationProject() {
      this.projectVisible = true;
    },
    /**
     * 关联机构
     */
    setOrg() {
      this.orgVisible = true;
    },
    /**
     * 关联角色
     */
    associationRole() {
      this.roleVisible = true;
    },
    /**
     * 是否启用
     * @param {String} val
     * @param {Object} row 当前数据
     * @param {Number} index 下标
     */
    async handleSwitchChange(val, row, index) {
      const { enableFlag, sysRoleUsers } = row;
      if (!sysRoleUsers) return;
      const params = {
        // 0：不启用；1：启用
        enableFlag: enableFlag === "1" ? "0" : "1",
        roleUserId: sysRoleUsers[0] ? sysRoleUsers[0].id : ""
      };
      const { success } = await this.$Model.setEnAbleFlag(params);
      if (success) {
        this.$message.success(`${enableFlag === "1" ? "关闭" : "启用"}成功`);
        this.getUserProject();
      }
    },
    // 设置权限
    setPermissions(row) {
      const { sysRoleUsers, projectId } = row;
      const roleId = sysRoleUsers[0] ? sysRoleUsers[0].id : "";
      if (!roleId) return;
      this.$router.push(`/project-roles?id=${projectId}&roleId=${roleId}`);
    },
    /**
     * 新增
     */
    handleAdd() {
      this.type = "add";
      this.currentData = {};
      this.visible = true;
    },
    /**
     * 编辑
     * @param {Object} row 当前数据
     */
    handleEdit(row) {
      this.type = "edit";
      this.currentData = { ...row };
      this.visible = true;
    },
    /**
     * 编辑机构
     */
    handleEditOrg() {
      if (!this.selectKey) {
        this.$message.warning("请选择机构");
        return;
      }
      this.eidtOrgVisible = true;
    },
    /**
     * 删除
     * @param {Object} row 当前数据
     */
    handleDelete(row) {
      this.$confirm("此操作将删除该项目, 是否继续?", "提示", {
        type: "warning"
      }).then(async () => {
        const projectIds = this.projectList
          .filter(v => v.projectId !== row.projectId)
          .map(v => v.projectId)
          .join(",");
        this.tableLoading = true;
        const { success } = await this.$Model.setUserProjectList({
          userId: this.userId,
          projectIds
        });
        this.tableLoading = false;
        if (success) {
          this.getUserProject();
          this.$message.success("删除成功");
        }
      });
    },
    /**
     * 选中机构
     */
    handleNodeClick(data) {
      this.selectKey = data.id;
      this.currentOrgData = { ...data };
    },
    /**
     * 保存
     * @param {Object} data 当前数据
     */
    async handleSave(data) {
      const params = {
        userId: this.userId,
        ...data
      };
      this.loading = true;
      const { success } = await this.$Model.singleRoleUserList(params);
      this.loading = false;
      if (success) {
        this.$message.success("保存成功");
        this.getUserProject();
        this.visible = false;
      }
    },
    /**
     * 关联项目
     * @param {Array} data 当前数据
     */
    async saveProject(data) {
      const params = {
        userId: this.userId,
        projectIds: data.join(",")
      };
      this.projectLoading = true;
      const { success } = await this.$Model.setUserProjectList(params);
      this.projectLoading = false;
      if (success) {
        this.getUserProject();
        this.$message.success("保存成功");
        this.projectVisible = false;
      }
    },
    /**
     * 编辑保存机构
     * @param {Array} data 当前数据
     */
    async saveOrg(data) {
      const params = {
        ...this.currentOrgData,
        ...data
      };
      this.eidtOrgLoading = true;
      const { success } = await this.$Model.setOrg(params);
      this.eidtOrgLoading = false;
      if (success) {
        this.getOrgById();
        this.$message.success("保存成功");
        this.eidtOrgVisible = false;
      }
    },
    /**
     * 关联机构
     * @param {Array} data 当前数据
     */
    async saveAssociationOrg(data) {
      const params = {
        userId: this.userId,
        orgId: data
      };
      this.orgLoading = true;
      const { success } = await this.$Model.userRelationOrg(params);
      this.orgLoading = false;
      if (success) {
        this.getOrgById();
        this.$message.success("保存成功");
        this.orgVisible = false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "../../assets/styles/table";
@import "../../assets/styles/dialog";

.user-detail-page {
  width: 100%;
  height: 100%;
  padding: 20px 30px;
  background-color: $baseBg;
  main {
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: $mainBg;
    .header {
      width: 100%;
      height: 100px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-bottom: 20px;
      .search-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .search-input {
          display: flex;
          ul {
            width: 400px;
            display: flex;
            li {
              width: 200px;
              height: 40px;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 16px;
              background-color: #fff;
              color: rgba(0, 0, 0, 0.8);
              cursor: pointer;
              transition: all 0.2s;
              &.active,
              &:hover {
                background: $linearG;
                color: #fff;
              }
              &:nth-child(1) {
                border-radius: 5px 0 0 5px;
              }
              &:nth-last-child(1) {
                border-radius: 0 5px 5px 0;
              }
            }
          }
          .input-container {
            width: 400px;
            display: flex;
            margin-left: 20px;
          }
          .el-input {
            margin-right: 20px;
          }
        }
      }
    }
    .table-container {
      width: 100%;
      height: calc(100% - 100px);
      .content {
        width: 100%;
        height: 100%;
        .el-row {
          margin: 80px 0;
          .label {
            display: inline-block;
            width: 200px;
            text-align: right;
          }
          .value {
            color: $mainColor;
          }
        }
        .el-tree {
          height: calc(100% - 40px);
          overflow-y: auto;
          background: $mainBg;
          color: #fff;
          /deep/ .el-tree-node__content {
            font-size: 16px;
            height: auto;
            margin-bottom: 20px;
            border-radius: 10px;
            transition: all 0.3s;
            .node-item {
              color: $mainColor;
              p {
                margin: 20px 0;
                .label {
                  color: #fff;
                  margin-right: 10px;
                }
              }
            }
            &:hover {
              color: $mainColor;
              background: $baseBg;
            }
          }
        }
        .el-tree {
          /deep/ .el-tree-node.is-current > .el-tree-node__content {
            color: $mainColor;
            background: $baseBg;
          }
          /deep/
            .el-tree-node.is-focusable:not(.is-current)
            > .el-tree-node__content {
            @include baseBgRgba();
          }
        }
      }
      /deep/ .el-table {
        height: calc(100% - 50px);
        .el-table__body-wrapper {
          height: calc(100% - 40px);
          overflow-y: auto;
          .btn {
            color: $mainColor;
            cursor: pointer;
            &:hover {
              text-decoration: underline;
            }
          }
        }
      }
    }
  }
}
</style>
